#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <iostream>

#include <QWebEngineView>
#include <QWebChannel>
#include <QMessageBox>
#include <QJsonObject>
#include <QJsonArray>


MainWindow::MainWindow(QWidget* parent) :
	QMainWindow(parent),
	ui(new Ui::MainWindow)
{
	ui->setupUi(this);
	qputenv("QTWEBENGINE_REMOTE_DEBUGGING", "7777");
	ui->text_recv->setReadOnly(true);

	// 与地图网页交互
	_myChannel = new MyChannel(this);						// 与网页js通讯的对象

	QWebChannel* web_channel = new QWebChannel(this);
	web_channel->registerObject("qtChannel", _myChannel);    // 向QWebChannel对象注册Qt对象

	page = ui->webengineview->page();
	page->setWebChannel(web_channel);
    ui->webengineview->load(QUrl("qrc:/smap/mymap_ba.html"));   // 加载页面

	// 绑定飞行器移动与停止的按钮事件
	QObject::connect(ui->btn_move, &QPushButton::clicked, this, &MainWindow::MoveToEast);

	//与服务器进行交互
	_tcpclient = new Client(this);      // 网络连接对象

	// 绑定发送信息按钮事件
	QObject::connect(ui->btn_send, &QPushButton::clicked, this, &MainWindow::SendInfo);
	QObject::connect(ui->btn_reconn, &QPushButton::clicked, this, &MainWindow::ReconnectToServer);
	// 将服务器发送过来的消息显示在文本框
	void(Client:: * clientSiganl)(QString) = &Client::SendWndData;		//函数指针，限定作用域
	void(MainWindow:: * wndSlot)(QString) = &MainWindow::WndDsplyData;	//函数指针，限定作用域
	QObject::connect(_tcpclient, clientSiganl, this, wndSlot);
}

MainWindow::~MainWindow()
{
	delete ui;
}

/// <summary>
/// 向东移动的函数调用
/// </summary>
void MainWindow::MoveToEast()
{
	if (ui->btn_move->text() == "Move to East") {
		// 向东移动
		_myChannel->MoveToEast(page);

		ui->btn_move->setText("Stop Move");
	}
	else {
		// 向东移动停止
		_myChannel->StopMoveToEast(page);

		ui->btn_move->setText("Move to East");
	}
}
/// <summary>
/// 发送消息
/// </summary>
void MainWindow::SendInfo()
{
	QString datastr = ui->text_send->toPlainText().trimmed();
	_tcpclient->UavSendData(datastr);

}
/// <summary>
/// 重连到服务器
/// </summary>
void MainWindow::ReconnectToServer() {
	_tcpclient->Reconnect();
}

/// <summary>
/// 发送消息
/// </summary>
void MainWindow::WndDsplyData(QString data)
{
	QDateTime dateTime = QDateTime::currentDateTime();		//获取系统当前的时间
	QString dt = dateTime.toString("yyyy-MM-dd hh:mm:ss");	//格式化时间
	QString str = QString("[%1] %2").arg(dt, data);
	ui->text_recv->appendPlainText(str);
}
